<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<!doctype html>
<html>
<title>ZingonTank</title>
<!--
<meta name="viewport" content="width=device-width , initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
-->
<%
    String sessionId=request.getSession().getId();
    request.getSession().setAttribute("sessionId",sessionId);
%>
<style type="text/css">
    .tankA {
        position: fixed;
        background: url("${pageContext.request.contextPath}/static/img/A.png");
        background-size: 100%;
        height: 70px;
        width: 101px;
    }
    .tankD {
        position: fixed;
        background: url("${pageContext.request.contextPath}/static/img/D.png");
        background-size: 100%;
        height: 70px;
        width: 101px;
    }
    .tankW {
        position: fixed;
        background: url("${pageContext.request.contextPath}/static/img/W.png");
        background-size: 100%;
        height: 101px;
        width: 70px;
    }
    .tankS {
        position: fixed;
        background: url("${pageContext.request.contextPath}/static/img/S.png");
        background-size: 100%;
        height: 101px;
        width: 70px;
    }

    .bullet {
        position: fixed;
        background: url("${pageContext.request.contextPath}/static/img/B.jpg");
        background-size: 100%;
        height: 20px;
        width: 20px;
    }
    .talk{
        height: 300px;
        width: 233px;
        left: 20px;
        bottom: 80px;
        position: fixed;
        overflow: hidden;
        background: rgba(0,0,0,.2);
    }
    .talk .content{
        height: 290px;
        width: 215px;
        left: 30px;
        bottom: 85px;
        position: fixed;
        overflow: hidden;
    }
    .eventMsg{
        height: 300px;
        width: 200px;
        right: 20px;
        top : 20px;
        position: fixed;
        overflow: hidden;
        background: rgba(0,0,0,.2);
    }
    .eventMsg .content{
        height: 290px;
        width: 180px;
        right: 30px;
        top: 25px;
        position: fixed;
        overflow: hidden;
    }
</style>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/layer.js"></script>

<body>
<video autoplay loop="loop" autobuffer="autobuffer"
       style="opacity: 1; visibility: visible;position: fixed; top: 0px; left: 0px;"
       src="//az29176.vo.msecnd.net/videocontent/HolidayDeer_GettyRF-473330017_768_ZH-CN.mp4"></video>
<a target="_blank" href="https://git.oschina.net/A_yes/WebSocketTank" style="position: fixed;right: 20px;bottom: 20px;">一起来维护该游戏吧</a>
<input hidden id="nickname">
<div id="con"></div>
<div class="talk">
    <div id="talk" class="content"></div>
</div>
<div class="eventMsg">
    <div id="eventMsg" class="content"></div>
</div>
<div style="left: 20px;bottom: 20px;position: fixed;">
    <textarea rows="3" cols="30" id="msg" onfocus="Talking()" onblur="Talking()" placeholder="在线聊天（最大长度50）（回车发送！）"></textarea>
</div>
<script type="text/javascript">
    var url = "ws://" + window.location.host + "${pageContext.request.contextPath}/tank2?a="
    var talkUrl = "ws://" + window.location.host + "${pageContext.request.contextPath}/talk?a="
    var sock = null;
    var talkSock=null;
    var con = document.getElementById("con");
    layer.prompt({
        title: '输入昵称(最大长度5)',
        formType: 0
    }, function (text, index) {
        if(text.length>5){
            alert("昵称过长");
            return;
        }
        document.getElementById("nickname").value=text;
        text=text+"_${sessionScope.get("sessionId")}";
        layer.close(index);
        var load = layer.load(0, {shade: false});
        url = url + text;
        talkUrl=talkUrl+text;
        sock = new WebSocket(url);
        talkSock=new WebSocket(talkUrl);
        sock.onmessage = function (e) {
            //console.log("action:", e.data);
            var obj = eval('(' + e.data + ')');
            if(obj.diedMsg!=null){
                console.log(obj.diedMsg);
                layer.alert(obj.diedMsg, {
                    time: 0 //不自动关闭
                    ,btn: ['原地复活', '随机复活']
                    ,yes: function(index){
                        layer.close(index);
                        talkSock.send("resA");
                    }
                    ,btn2: function(index){
                        layer.close(index);
                        talkSock.send("resB");
                    }
                });
            }
            draw(e.data);
            if (window.DeviceMotionEvent) {
                window.addEventListener('deviceorientation',
                        deviceMotionHandler, false);
                window.addEventListener('touchstart', touches, false);
            }
            layer.close(load);
        }

        sock.onclose = function () {
            console.log("close");
            layer.msg("连接中断，请刷重试。");
        }

        talkSock.onmessage=function (e){
            var obj = eval('(' + e.data + ')');
            console.log(obj.talkMsg);
            if(obj.eventMsg!=null) {
                drawEvent(obj.eventMsg);
            }
            if(obj.talkMsg!=null){
                drawTalk(obj.talkMsg);
            }
        }

        document.onkeydown = keyDown;
        document.onkeyup = keyUp;
    });

    var isUp = false;
    var isDown=false;
    var isLeft=false;
    var isRight=false;
    var isShoting=false;
    var isTalking=false;
    var oldCmd = "action"
            + (isUp ? "_W" : "")
            + (isDown ? "_S" : "")
            + (isLeft ? "_A" : "")
            + (isRight ? "_D" : "")
            + (isShoting ? "_J" : "");

    function keyDown(key) {
        var realkey = String.fromCharCode(key.which);
        if(isTalking)
            return;
        if (realkey == "W" || key.which == 38)
            isUp = true;
        if (realkey == "S" || key.which == 40)
            isDown = true;
        if (realkey == "A" || key.which == 37)
            isLeft = true;
        if (realkey == "D" || key.which == 39)
            isRight = true;
        if (realkey == "J")
            isShoting = true;
        sendAction();

    }


    function keyUp(key) {
        var realkey = String.fromCharCode(key.which);
        if(isTalking){
            if(key.which==13){
                if(document.getElementById("msg").value.length>50){
                    layer.msg("消息最大长度 50");
                    return;
                }
                if(document.getElementById("msg").value.length<=1){
                    document.getElementById("msg").value=null;
                    return;
                }

                talkSock.send(document.getElementById("nickname").value+" : "+document.getElementById("msg").value);
                document.getElementById("msg").value="";
            }
        }
        if (realkey == "W" || key.which == 38)
            isUp = false;
        if (realkey == "S" || key.which == 40)
            isDown = false;
        if (realkey == "A" || key.which == 37)
            isLeft = false;
        if (realkey == "D" || key.which == 39)
            isRight = false;
        if (realkey == "J")
            isShoting = false;
        sendAction();
    }

    function sendAction() {
        var cmd = "action"
                + (isUp ? "_W" : "")
                + (isDown ? "_S" : "")
                + (isLeft ? "_A" : "")
                + (isRight ? "_D" : "")
                + (isShoting ? "_J" : "");
        if(oldCmd===cmd){
            return;
        }
        oldCmd=cmd;
        console.log(oldCmd);
        talkSock.send(oldCmd);
    }

    function draw(data) {
        con.innerHTML = "";
        var obj = eval('(' + data + ')');
        if (obj.T != null)
            drawTank(obj.T);
        if (obj.B != null)
            drawBullet(obj.B);

    }

    function drawTank(tank) {
        var con = document.getElementById("con");
        for (var i=0;i<tank.length;i++) {//遍历json对象的每个key/value对,p为key
            var node = document.createElement('div');
            node.setAttribute("class", "tank"+tank[i].d);
            node.setAttribute("style", "left:" + tank[i].x + "px;top:"
                    + tank[i].y + "px;")
            node.innerHTML = tank[i].n;
            con.appendChild(node);
        }
    }

    function drawBullet(bullet) {
        var con = document.getElementById("con");
        for (var p in bullet) {//遍历json对象的每个key/value对,p为key
            var node = document.createElement('div');
            node.setAttribute("class", "bullet");
            node.setAttribute("style", "left:" + bullet[p].x + "px;top:"
                    + bullet[p].y + "px;");
            con.appendChild(node);
        }
    }

    function drawTalk(e){
        var talkCon=document.getElementById("talk");
        var msg=document.createElement("h3");
        msg.setAttribute("style","color:#4b5ffb;");
        msg.innerHTML= e;
        talkCon.appendChild(msg);
        var b=document.getElementById("talk").scrollHeight;
        document.getElementById("talk").scrollTop=b;
    }

    function drawEvent(e){
        var eventMsg=document.getElementById("eventMsg");
        var msg=document.createElement("h4");
        msg.setAttribute("style","color:red;");
        msg.innerHTML= e;
        eventMsg.appendChild(msg);
        var b=document.getElementById("eventMsg").scrollHeight;
        document.getElementById("eventMsg").scrollTop=b;
    }

    function Talking(){
        isTalking=!isTalking;
    }

    function deviceMotionHandler(eventData) {
        var realkey = "";
        if (talkSock == null)
            return;
        if (eventData.beta > 25)
            isDown = true;
        else
            isDown = false;
        if (eventData.beta < -10)
            isUp = true;
        else
            isUp = false;
        if (eventData.gamma > 20)
            isRight = true;
        else
            isRight = false;
        if (eventData.gamma < -20)
            isLeft = true;
        else
            isLeft = false;
        sendAction();
    }

    function touches(e) {
        //e.preventDefault();
        if (talkSock == null)
            return;
        isShoting=!isShoting;
        sendAction();
    }
</script>
</body>
</html>
